package com.hs.sqlite3.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hs.sqlite3.utils.HttpUtils;
import com.hs.sqlite3.utils.JsonRequestExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SqlitService {
    @Value("${urldata}")
    String urldata;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public String comsum(String tableName,String ur){
        System.out.println("table：" + tableName +"   |  url " + ur);
        String selectUserData = "select * from " + tableName;
        List<Map<String, Object>> list = jdbcTemplate.queryForList(selectUserData);
        if(list.size() == 0){
            System.out.println("sqlite无数据库 ，不需要推送！");
            return "无数据";
        }
        List<Integer> ids = new ArrayList<>();
        for (Map<String, Object> map : list) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if(entry.getKey().equals("id") || entry.getKey().equals("ID")){
                    ids.add(Integer.valueOf(entry.getValue().toString()));
                }
            }
        }
        String url = urldata + ur;//提交消费
        String s = JsonRequestExample.post(url,JSONArray.toJSON(list).toString());
        JSONObject jsonResult = (JSONObject) JSONObject.parse(s);
        System.out.println("返回结果："+ s);
        System.out.println("返回json格式化结果："+ jsonResult.toString());
        String code = jsonResult.get("code").toString();
        String data = jsonResult.get("data").toString();
        if(200 == Integer.valueOf(code) && Integer.valueOf(data) > 0){
            System.out.println("推送成本，删除 ===========" + ids);
            String idsss = ids.toString();
            idsss = idsss.replaceAll("\\[","\\(");
            idsss = idsss.replaceAll("\\]","\\)");
            String del = "delete from  " +  tableName + " where id in  " + idsss ;
            jdbcTemplate.update(del);
        }else{
            System.out.println("推送失败，不删除  ===========" + ids);
        }
        return s;
    }


}
